package com.ccut.xunfeiSpringboot.controller;

import com.ccut.xunfeiSpringboot.service.FaceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/face")
@CrossOrigin(origins = "http://localhost:8080")
public class FaceController {

    private static final Logger logger = LoggerFactory.getLogger(FaceController.class);

    @Autowired
    private FaceService faceService;

    @PostMapping("/analyze")
    public ResponseEntity<String> analyzeFace(@RequestParam("file") MultipartFile file) {
        logger.info("收到人脸分析请求，文件名: {}", file.getOriginalFilename());

        try {
            if (file.isEmpty()) {
                logger.warn("上传文件为空，文件名: {}", file.getOriginalFilename());
                return ResponseEntity.badRequest().body("上传的文件为空");
            }

            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.contains(".")) {
                logger.warn("无法识别的文件格式，文件名: {}", originalFilename);
                return ResponseEntity.badRequest().body("无法识别的文件格式");
            }

            String imageFormat = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            if (!imageFormat.equals("jpg") && !imageFormat.equals("jpeg") && !imageFormat.equals("png")) {
                logger.warn("不支持的图片格式: {}", imageFormat);
                return ResponseEntity.badRequest().body("仅支持 JPG、JPEG、PNG 格式的图片");
            }

            logger.debug("开始处理图片文件，格式: {}，大小: {} bytes", imageFormat, file.getSize());
            String result = faceService.analyzeFace(file.getBytes(), imageFormat);
            logger.info("人脸分析成功，结果长度: {}", result.length());

            return ResponseEntity.ok(result);
        } catch (IOException e) {
            logger.error("文件处理失败，文件名: {}，错误信息: {}", file.getOriginalFilename(), e.getMessage(), e);
            return ResponseEntity.status(500).body("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("人脸分析发生意外错误，文件名: {}，错误类型: {}，错误信息: {}",
                    file.getOriginalFilename(),
                    e.getClass().getSimpleName(),
                    e.getMessage(),
                    e);
            return ResponseEntity.status(500).body("内部服务器错误: " + e.getMessage());
        }
    }
}